/*
 * @Author: wangjq4214
 * @Date: 2022-04-17 19:49:54
 * @LastEditTime: 2022-06-07 19:04:22
 * @LastEditors: wangjq4214
 */
package main

import (
	"context"
	"log"

	"gitee.com/wangjq4214/schedule/proto"
	pb "gitee.com/wangjq4214/schedule/proto/follower"
)

type Server struct {
	pb.UnimplementedFollowerServeServer

	commitChan chan Task
	newChan    chan *[]Task
}

func NewServer(commitChan chan Task, newChan chan *[]Task) *Server {
	return &Server{
		commitChan: commitChan,
		newChan:    newChan,
	}
}

func (s *Server) NewTask(ctx context.Context, req *pb.NewTaskReq) (*pb.NewTaskRes, error) {
	tmp := make([]Task, 0)
	for _, item := range req.GetItem() {
		tmp = append(tmp, Task{
			CPU:     int(item.GetCPU()),
			Storage: int(item.GetStorage()),
			Time:    item.GetTime(),
			Need:    item.GetNeed(),
			Position: DataPosition{
				ID: item.GetPosition().GetID(),
				IP: item.GetPosition().GetIP(),
			},
		})
	}
	s.newChan <- &tmp

	log.Printf("Get %v new tasks\n", len(tmp))

	return &pb.NewTaskRes{
		Status: &proto.Status{
			Code: 0,
			Msg:  "success",
		},
	}, nil
}

func (s *Server) CommitTask(ctx context.Context, req *pb.CommitTaskReq) (*pb.CommitTaskRes, error) {
	s.commitChan <- Task{
		UUID: req.GetID(),

		CPU:     int(req.GetCPU()),
		Storage: int(req.GetStorage()),
		Time:    req.GetTime(),
		Need:    req.GetNeed(),

		Position: DataPosition{
			ID: req.GetPosition().GetID(),
			IP: req.GetPosition().GetIP(),
		},
	}

	return &pb.CommitTaskRes{
		Status: &proto.Status{
			Code: 0,
			Msg:  "success",
		},
	}, nil
}
func (s *Server) GetData(req *pb.GetDataReq, server pb.FollowerServe_GetDataServer) error {
	tmp := int(req.GetID())
	if tmp < 0 {
		tmp = 0
	}

	for i := 0; i < tmp; i++ {
		server.Send(&pb.GetDataRes{
			Status: &proto.Status{
				Code: 0,
				Msg:  "success",
			},
			Data: make([]byte, 1024),
		})
	}

	return nil
}
